<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */

namespace App\Eloquent\Ygt;
use App\Eloquent\Oa\FlowCustomerOrder;
use App\Engine\Func;
use Framework\Services\Push\JPush\JPushService;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User;

//use DB;

class UserMessage extends DbEloquent{

    use SoftDeletes;
    protected $dates = ['deleted_at'];
    protected $table = 'ygt_user_message';
    //添加一个工单消息
    public static function sendOrderMessage($data,$foreignType=1)
    {
        $result     = self::putInData($data,$foreignType);
        return $result;
    }
    //添加一个材料消息
    public static function sendProductOrderMessage($data,$foreignType=2)
    {
        $result     = self::putInData($data,$foreignType);
        return $result;
    }
    //添加一个订单消息
    public static function sendCustomerOrderMessage($data,$foreignType=3)
    {
        $result     = self::putInData($data,$foreignType);
        return $result;
    }
    //添加一个采购消息
    public static function sendWorkFlowMessage($data,$foreignType=4)
    {
        $result     = self::putInData($data,$foreignType);
        return $result;
    }
    //发送消息
    //$data['to_user_id']不为空给人发消息 为空给角色发消息
    public static function putInData($data,$foreignType=0)
    {
        $fieldList              = [
            ['name'=>'company_id','value'=>0],['name'=>'privilege_id','value'=>0],
            ['name'=>'foreign_type','value'=>$foreignType], ['name'=>'foreign_key','value'=>0],
            ['name'=>'form_user_id','value'=>0], ['name'=>'to_user_id','value'=>0],
            ['name'=>'type','value'=>0], ['name'=>'type_id','value'=>0],
            ['name'=>'type_status','value'=>1], ['name'=>'title','value'=>''],
            ['name'=>'content','value'=>''],['name'=>'theme','value'=>''],
            ['name'=>'is_read','value'=>0],
        ];
        $tableData              = [
            'created_at'=>$_SERVER['REQUEST_TIME'],'updated_at'=>$_SERVER['REQUEST_TIME'],
        ];
        foreach($fieldList as $key=>$val)
        {
            $valName            = $val['name'];
            $valValue           = $val['value'];
            $dataValue          = isset($data[$valName]) ? $data[$valName] : $valValue;
            $tableData[$valName]= $dataValue;
        }
        $dataUserId             = isset($data['to_user_id']) ? $data['to_user_id'] : '';
        $dataPrivilegeId        = $data['privilege_id'];
        $dataCompanyId          = $data['company_id'];
        if($dataUserId){
            //给指定的人发消息
            $userArr            = explode(',', $dataUserId );
            $where              = ['company_id'=>$dataCompanyId,'user_id'=>['in',$userArr]];
            $tableData['privilege_id']= 0;
        }else{
            //给指定的角色发消息
            $where              = ['company_id'=>$dataCompanyId,'privilege_id'=>$dataPrivilegeId];
        }
        $userList               = DepartmentUser::getList( $where )->toArray();
        if($userList){
            $dbData             = $mobileArr = [];
            $title              = '您有一个新信息';
            $jpush              = new JPushService();
            foreach( $userList as $key=>$val){
                $arr                    = $tableData;
                $arr['to_user_id']    = $val['user_id'];
                //获得发送用户的名称
                $form_user_id = $arr['form_user_id'];
                $truename = \App\Eloquent\Ygt\User::getOneValueById($form_user_id,'truename');
                $arr['form_user_name'] = $truename;

                $dbData[]               = $arr;
                $mobileArr[]            = $val['mobile'];

                $where                  = ['is_read'=>0,'to_user_id'=>$val['user_id']];
                $messageCount           = self::getCount($where);
                $iosArr                 = [
                    'badge'=>$messageCount,
                    'extras'=>[
                        'type'=>1,
                    ],
                ];
                $androidArr             = [
                    'extras'=>[
                        'type'=>1,
                    ],
                ];
                $jpush->sendByMobile( $val['mobile'],$title,$iosArr,$androidArr );
            }
            $result             = self::insert( $dbData );
            //发送推送消息
//            if( $mobileArr ){
//                $title          = '您有一个新信息';
//                $jpush          = new JPushService();
//                $jpush->sendByMobile( $mobileArr, $title );
//            }
        }else{
            $result             = false;
        }
        return $result;
    }
    //取消息分组列表
    public static function getListByForeignType($whereArr,$userId,$foreignType=0,$limit=0,$offset=0)
    {
        $query              = static::query();
        $queryCount         = static::query();
        //取消息列表
        $selectSql          = 'MAX(id) AS xid,foreign_type,foreign_key';
        $query              = $query->selectRaw($selectSql);
        $query              = $query->where('to_user_id',$userId);
        $queryCount         = $queryCount->where('to_user_id',$userId);
        if($foreignType != 0)
        {
            $query          = $query->where('foreign_type',$foreignType);
        }
        if( isset($whereArr['company_id']) )
        {
            $companyId      = $whereArr['company_id'];
            $query          = $query->where('company_id',$companyId);
            $queryCount     = $queryCount->where('company_id',$companyId);
        }
        if( isset($whereArr['created_at']) )
        {
           $query          = $query->whereBetween('created_at',$whereArr['created_at']);
           $queryCount     = $queryCount->whereBetween('created_at',$whereArr['created_at']);
        }
        //$query              = $query->limit($limit)->offset($offset);;
        $query              = $query->orderByDesc('xid');
        $query              = $query->groupBy('foreign_type','foreign_key');
        $queryList          = $query->get()->toArray();
        $messageIdArr       = [];
        foreach($queryList as $key=>$val)
        {
            $messageIdArr[] = $val['xid'];
        }
        $lists              = [];
        $count              = $readCount = 0;
        if($messageIdArr)
        {
            //取消息列表总数
            $selectSql          = 'COUNT(DISTINCT foreign_type,foreign_key) AS num';
            $queryCount         = $queryCount->selectRaw($selectSql);
            $countStd           = $queryCount->first();
            $count              = $countStd->num;
            //取未读消息总数
            $query              = static::query();
            $selectSql          = 'count(id) as num';
            $query              = $query->selectRaw($selectSql);
            $query              = $query->where('is_read',0);
            $query              = $query->where('to_user_id',$userId);
            $object             = $query->first();
            $readCount          = $object->num;
            //转换列表的列表的内容
            $lists              = self::transformListByIdArr($messageIdArr,$userId);
        }
        $result             = ['lists'=>$lists,'count'=>$count,'read_count'=>$readCount];
        return $result;
    }
    public static function transformListByIdArr($idArr,$userId)
    {
        $foreignTypeList        = [
            ['id'=>1,'title'=>'工单'],['id'=>2,'title'=>'材料'],
            ['id'=>3,'title'=>'订单'],['id'=>4,'title'=>'采购'],
        ];
        $typeListArr            = config('message.type_list');
        $foreignTypeArr         = $foreignTypeInArr = $foreignKeyInArr = [];
        foreach($foreignTypeList as $key=>$val)
        {
            $foreignTypeArr[$val['id']] = [];
        }
        $detailArr              = [
            'id'=>0,
            'order_type'=>'',
            'order_title'=>'',
            'product_name'=>'',
            'product_num'=>'',
            'finished_specification'=>'',
            'finished_date'=>'',
            'created_at'=>'',
            'status'=>'',
            'production_case_diagram'=>'',
            'field_name_23'=>'',
            'icon_url'=>'',
            'order_type_title'=>'',
            '$orderStatus'=>'',
            '$statusColor'=>'',
            'productOrderTime'=>'',
            'seller_company_name'=>'',
            'money'=>0,
            'purchase_number'=>'',
            'product_text'=>'',
        ];
        $iconUrlDefault         = env('APP_URL').'/assets/mobile/common/images/order_list_default.png';
        $query                  = static::query();
        $selectSql              = 'ygt_user_message.id';
        $selectSql              .= ',ygt_user_message.foreign_type,ygt_user_message.foreign_key,ygt_user_message.form_user_name';
        $selectSql              .= ',ygt_user_message.type,ygt_user_message.type_id,ygt_user_message.type_status';
        $selectSql              .= ',ygt_user_message.title,ygt_user_message.content';
        $selectSql              .= ',ygt_user_message.is_read,ygt_user_message.theme,ygt_user_message.created_at';
        $selectSql              .= ',ygt_user.truename';
        $query                  = $query->selectRaw($selectSql);
        $query                  = $query->leftJoin('ygt_user', 'ygt_user.id', '=', 'ygt_user_message.form_user_id');
        $query                  = $query->whereIn('ygt_user_message.id',$idArr);
        $query                  = $query->orderByDesc('id');
        $listsData              = $query->get()->toArray();
        $lists                  = [];
        foreach ($listsData as $key=>$val)
        {
            $temp               = $val;

            $valCreatedAt       = $val['created_at'];
            $valCreatedAtYmd    = date('Y-m-d',$valCreatedAt);
            $temp['last_time']  = $valCreatedAtYmd ? $valCreatedAtYmd : '';

            $valType            = $val['type'];
            $theme              = isset($typeListArr[$valType]) ? $typeListArr[$valType] : '新消息';
            $theme              = !empty($val['theme'])?$val['theme']:$theme;
            if(!empty($val['form_user_name'])){
                $val['truename'] = $val['form_user_name'];
            }
            $temp['content']    = $val['truename'].': '.$theme;

            //取相关未读消息的总数
            $temp['read_number'] = 0;

            $temp['icon_url']   = $iconUrlDefault;
            $temp['detail']     = $detailArr;

            $lists[]            = $temp;

            $valForeignType     = $val['foreign_type'];
            $valForeignKey      = $val['foreign_key'];
            if(!in_array($valForeignType,$foreignTypeInArr))
            {
                $foreignTypeInArr[] = $valForeignType;
            }
            if(!in_array($valForeignKey,$foreignKeyInArr))
            {
                $foreignKeyInArr[]  = $valForeignKey;
            }
            $foreignTypeArr[$valForeignType][]   = $valForeignKey;
        }
        //取相关未读消息的总数
        $query              = static::query();
        $selectSql          = 'foreign_type,foreign_key,count(1) as num';
        $query              = $query->selectRaw($selectSql);
        $query              = $query->whereIn('foreign_type',$foreignTypeInArr);
        $query              = $query->whereIn('foreign_key',$foreignKeyInArr);
        $query              = $query->where('to_user_id',$userId);
        $query              = $query->where('is_read',0);
        $query              = $query->groupBy('foreign_type','foreign_key');
        $numberList         = $query->get()->toArray();
        foreach ($lists as $key=>$val)
        {
            foreach ($numberList as $k=>$v)
            {
                if($val['foreign_type'] == $v['foreign_type'] && $val['foreign_key'] == $v['foreign_key'])
                {
                    $lists[$key]['read_number'] = $v['num'];
                }
            }
        }
        //在这里把总的数据切割成两部分,一部分是包含了未读消息,一部分是包含的消息全部已读
        //只保存对应的id 就行,因为这里的id是按照有由大到小的顺序排的
        //之后是在原有的基础上再进行排序,有未读的在前,全部已读的在后
        $listsOne               = $listsTwo = [];
        foreach($lists as $key=>$val)
        {
            if($val['read_number']>0){
                $listsOne[]     = $val['id'];
            }else{
                $listsTwo[]     = $val['id'];
            }
        }
        $listsSortArr           = array_merge($listsOne,$listsTwo);
        //若消息是工单消息,相关数据内容转换
        $temForeignTypeArr      = isset($foreignTypeArr[1]) ? $foreignTypeArr[1] : [];
        if($temForeignTypeArr)
        {
            $orderList          = Order::whereIn('id',$temForeignTypeArr)->get()->toArray();
            $lists              = self::changeListByOrderList($lists,$orderList);
        }
        //若消息是材料消息,相关数据内容转换
        $temForeignTypeArr      = isset($foreignTypeArr[2]) ? $foreignTypeArr[2] : [];
        if($temForeignTypeArr)
        {
            $productList        = [];
            $lists              = self::changeListByProductList($lists,$productList);
        }
        //若消息是订单消息,相关数据内容转换
        $temForeignTypeArr      = isset($foreignTypeArr[3]) ? $foreignTypeArr[3] : [];
        if($temForeignTypeArr)
        {
            $customerList       = FlowCustomerOrder::withTrashed()->whereIn('id',$temForeignTypeArr)->get()->toArray();
            $lists              = self::changeListByCustomerOrderList($lists,$customerList);
        }
        //若消息是采购消息,相关数据内容转换
        $temForeignTypeArr      = isset($foreignTypeArr[4]) ? $foreignTypeArr[4] : [];
        if($temForeignTypeArr)
        {
            //创建采购单之后，采购主管消息列表页面收到的消息主题是“采购到货”的内容都是空的，
            //主题应该是改成供应商的名称，内容要改成采购金额和交货日期
            $workflowList       = \App\Eloquent\Oa\Workflow::whereIn('id',$temForeignTypeArr)->get()->toArray();
            $lists              = self::changeListByWorkflowList($lists,$workflowList);
        }
        //列表排序问题,原因之前的数据,经过不同类型消息显示不同内容时顺序乱掉了
        $result                 = [];
        foreach($listsSortArr as $key=>$val)
        {
            foreach($lists as $k=>$v)
            {
                if($v['id'] == $val)
                {
                    $result[]       = $v;
                }
            }
        }
        return $result;
    }
    public static function changeListByOrderList($data,$list)
    {
        $fieldArrTemp       = [
            'field_name_23','product_name','finished_specification',
            'product_num','finished_date','order_title', 'order_type',
            'id','production_case_diagram','status','created_at','chip_specification_length'
        ];
        $statusList         = [
            '1'=>['txt'=>'待接单','color'=>'FFB401'],'101'=>['txt'=>'待开工','color'=>'FFB401'],
            '2'=>['txt'=>'生产中','color'=>'FE7E57'],'3'=>['txt'=>'已完工','color'=>'04C9B3'],
        ];
        $tempArr            = self::getOrderNeedFieldData($list,$fieldArrTemp,$statusList);
        foreach($data as $key=>$val)
        {
            $valForeignType = $val['foreign_type'];
            $valForeignKey  = $val['foreign_key'];
            if($valForeignType == 1)
            {
                if(isset($tempArr[$valForeignKey]))
                {
                    $data[$key]['detail']   = $tempArr[$valForeignKey];
                    $data[$key]['detail']['purchase_number']        = '';
                    $data[$key]['detail']['product_text']        = '';
                }
            }
        }
        return $data;
    }
    public static function changeListByProductList($data,$list)
    {
        return $data;
    }
    public static function changeListByCustomerOrderList($data,$list)
    {
        $fieldArrTemp       = [
            'field_name_23','product_name','finished_specification',
            'product_num','finished_date','order_title', 'order_type',
            'id','production_case_diagram','status','created_at','is_deal_price','chip_specification_length'
        ];
        $statusList         = config('order.customer_order_status_list');
        $tempArr            = self::getOrderNeedFieldData($list,$fieldArrTemp,$statusList);
        foreach($data as $key=>$val)
        {
            $valForeignType = $val['foreign_type'];
            $valForeignKey  = $val['foreign_key'];
            if($valForeignType == 3)
            {
                if(isset($tempArr[$valForeignKey]))
                {
                    $data[$key]['detail']   = $tempArr[$valForeignKey];
                    $data[$key]['detail']['purchase_number']        = '';
                    $data[$key]['detail']['product_text']        = '';
                }
                if(!empty($tempArr[$valForeignKey]['icon_url']))
                {
                    $data[$key]['icon_url']   = $tempArr[$valForeignKey]['icon_url'];
                }
            }
        }
        return $data;
    }
    //办公申请
    public static function changeListByWorkflowList($data,$lists)
    {
        $tempArr            = self::getPurchaseListArr($lists);
        foreach($data as $key=>$val)
        {
            $valForeignType = $val['foreign_type'];
            $valForeignKey  = $val['foreign_key'];
            if($valForeignType==4)
            {
                if(isset($tempArr[$valForeignKey]))
                {
                    $temp           = $tempArr[$valForeignKey];

                    $temp['purchase_number'] = \App\Engine\Common::changeSnCode($temp['purchase_number']);
                    $data[$key]['detail']['finished_date']          = $temp['finished_date'];
                    $data[$key]['detail']['seller_company_name']   = $temp['seller_company_name'];
                    $data[$key]['detail']['money']                  = $temp['money'];
                    $data[$key]['detail']['purchase_number']        = $temp['purchase_number'];
                    $data[$key]['detail']['product_text']        = $temp['product_text'];

                    $userId = \App\Engine\Func::getHeaderValueByName('userid');
                    $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
                    if($userInfo['privilege_id'] == 102){//处理供应商的小秘书需要展示工厂名称而不是供应商名称
                        if(!isset($temp['company_id'])){
                            continue;
                        }

                        $companyId = $temp['company_id'];
                        $companName = '';
                        $companyRow = \App\Eloquent\Ygt\Company::where(['id'=>$companyId])->first();
                        if($companyRow){
                            $companName = $companyRow->title;
                        }

                        $data[$key]['detail']['seller_company_name']   = $companName;
                    }

                }
            }
        }
        return $data;
    }
    public static function getPurchaseListArr($lists)
    {
        $result                     = $purchaseIdArr = $returnPurchaseIdArr = [];
        $purchaseType               = 26;
        $returnPurchaseType         = 27;
        foreach($lists as $key=>$val)
        {
            $valId                  = $val['id'];
            $valRelatedType         = $val['related_type'];
            $valRelatedId           = $val['related_id'];
            if($valRelatedType == $purchaseType){
                $purchaseIdArr[]        = $valRelatedId;
            }else if($valRelatedType == $returnPurchaseType){
                $returnPurchaseIdArr[]  = $valRelatedId;
            }
            $result[$valId]         = [
                'related_type'=>$valRelatedType,
                'related_id'=>$valRelatedId,
                'seller_company_id'=>0,
                'finished_date'=>'',
                'seller_company_name'=>config('default-value.purchase_list_default_supplier_name'),
                'money'=>0,
                'purchase_number'=>'',
                'product_text'=>'',
            ];
        }
        $sellerCompanyIdArr         = [];
        //采购单列表
        if(!empty($purchaseIdArr))
        {
            //采购信息
            $column                 = 'id';
            $purchaseList           = \App\Eloquent\Ygt\Purchase::whereIn($column,$purchaseIdArr)->get()->toArray();
            foreach($result as $key=>$val)
            {
                $valRelatedType     = $val['related_type'];
                $valRelatedId       = $val['related_id'];
                if($valRelatedType==$purchaseType)
                {
                    $finishedDate       = '';
                    $purchaseNumber       = '';
                    $sellerCompanyId    = 0;
                    foreach($purchaseList as $k=>$v)
                    {
                        if($valRelatedId==$v['id'])
                        {
                            $finishedDate       = $v['finished_date'];
                            $sellerCompanyId    = $v['supplier_id'];
                            $purchaseNumber    = $v['purchase_number'];
                        }
                    }
                    $result[$key]['finished_date']  = "交货日期: ".$finishedDate;
                    $result[$key]['seller_company_id']  = $sellerCompanyId;
                    $result[$key]['purchase_number']  = "采购单号: ".$purchaseNumber;
                    $result[$key]['company_id']  = $v['company_id'];//保存采购单的企业ID，后面会用到
                    if($sellerCompanyId > 0)
                    {
                        $sellerCompanyIdArr[]   = $sellerCompanyId;
                    }
                }
            }

            //采购材料信息
            $column                 = 'purchase_id';
            $materialList           = \App\Eloquent\Ygt\PurchaseMaterial::whereIn($column,$purchaseIdArr)->get()->toArray();
            foreach($result as $key=>$val)
            {
                $valRelatedType     = $val['related_type'];
                $valRelatedId       = $val['related_id'];
                if($valRelatedType==$purchaseType)
                {
                    $money          = 0;
                    $productArr     = [];
                    foreach($materialList as $k=>$v)
                    {
                        if($valRelatedId==$v['purchase_id'])
                        {
                            $tempMoney          = $v['num']*$v['price'];
                            $money              += $tempMoney;
                            $product            = \App\Eloquent\Ygt\Product::where('id',$v['material_id'])->first();
                            if($product)
                            {
                                $productArr[]   = $product->product_name;
                            }
                        }
                    }
                    $result[$key]['money']      = $money;
                    $productText                = implode(',',$productArr);
                    $result[$key]['product_text']      = '材料: '.$productText;
                }
            }
        }
        //退货单列表
        if(!empty($returnPurchaseIdArr))
        {
            //退货信息
            $column                 = 'id';
            $returnPurchaseList     = \App\Eloquent\Ygt\ReturnPurchase::whereIn($column,$returnPurchaseIdArr)->get()->toArray();
            foreach($result as $key=>$val)
            {
                $valRelatedType     = $val['related_type'];
                $valRelatedId       = $val['related_id'];
                if($valRelatedType==$returnPurchaseType)
                {
                    $finishedDate       = '';
                    $sellerCompanyId    = 0;
                    foreach($returnPurchaseList as $k=>$v)
                    {
                        if($valRelatedId==$v['id'])
                        {
                            $finishedDate       = '';
                            $sellerCompanyId    = $v['supplier_id'];
                        }
                    }

                    $result[$key]['finished_date']  = $finishedDate;


                    $result[$key]['seller_company_id']  = $sellerCompanyId;
                    $result[$key]['purchase_number']  = "退货单号: ".$v['purchase_number'];
                    if($sellerCompanyId > 0)
                    {
                        $sellerCompanyIdArr[]   = $sellerCompanyId;
                    }
                }
            }
            //退货材料信息
            $column                 = 'purchase_id';
            $materialList           = \App\Eloquent\Ygt\ReturnPurchaseMaterial::whereIn($column,$returnPurchaseIdArr)->get()->toArray();
            foreach($result as $key=>$val)
            {
                $valRelatedType     = $val['related_type'];
                $valRelatedId       = $val['related_id'];
                if($valRelatedType==$returnPurchaseType)
                {
                    $money          = 0;
                    $productArr     = [];
                    foreach($materialList as $k=>$v)
                    {
                        if($valRelatedId==$v['purchase_id'])
                        {
                            $tempMoney          = $v['num']*$v['price'];
                            $money              += $tempMoney;
                            $product            = \App\Eloquent\Ygt\Product::where('id',$v['material_id'])->first();
                            if($product)
                            {
                                $productArr[]   = $product->product_name;
                            }
                        }
                    }
                    $result[$key]['money']      = $money;
                    //特殊处理，这个字段退货消息改为退货金额 zhuyujun 20180925
                    $result[$key]['finished_date']  = "退货金额: ¥".$money;

                    $productText                = implode(',',$productArr);
                    $result[$key]['product_text']      = '材料: '.$productText;
                }
            }
        }
        //取供应商名称
        if(!empty($sellerCompanyIdArr))
        {
            $where                  = ['id'=>['in',$sellerCompanyIdArr]];
            $sellerCompanyCollection= \App\Eloquent\Ygt\SellerCompany::getList($where);
            $sellerCompanyArr       =$sellerCompanyCollection->pluck('title', 'id');
            foreach($result as $key=>$val)
            {
                $sellerCompanyId        = $val['seller_company_id'];
                if(isset($sellerCompanyArr[$sellerCompanyId]))
                {
                    $result[$key]['seller_company_name']    = $sellerCompanyArr[$sellerCompanyId];
                }
            }
        }
        return $result;
    }

    //取消息表app中需要的字段信息
    public static function getNeedFieldData($lists,$fieldArr)
    {
        $result             = [];
        foreach($lists as $key=>$val)
        {
            $arrTemp        = [];
            foreach($val as $k=>$v)
            {
                if(in_array($k,$fieldArr))
                {
                    $arrTemp[$k]    = $v;
                }
            }
            $result[]       = $arrTemp;
        }
        return $result;
    }
    //取订单和工单app中需要的字段信息
    public static function getOrderNeedFieldData($lists,$fieldArr,$statusList)
    {
        $result                 = [];
        $orderListData          = self::getNeedFieldData($lists,$fieldArr);
        foreach ($orderListData as $key=>$val)
        {
            $tempArr            = $val;

            $valId              = $val['id'];
            $valProductionCaseDiagram   = isset($val['production_case_diagram']) ? intval($val['production_case_diagram']) : 0;
            $imgUrl             = Func::getImgUrlById($valProductionCaseDiagram);
            $iconUrl            = $imgUrl ? $imgUrl : '';
            $tempArr['icon_url']        = $iconUrl;

            $tempProductNum             = $val['product_num'];
            $tempProductNum             = str_replace(',', '', $tempProductNum);
            $tempArr['product_num']   = $tempProductNum;
            $tempArr['field_name_23'] = \App\Engine\Process::changeFieldName23($val['field_name_23']);

            //转换品名 20180626 zhuyujun
            $tempProductName            = $val['product_name'];
            $buyersProduct = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$tempProductName])->first();
            if ($buyersProduct) {
                $tempArr['product_name'] = $buyersProduct['name'];
            }


//            $finishedSpecification      = $val['finished_specification'];
            //调整为片料规格-字段名称不变 zhuyujun 20181206
            $finishedSpecification      = $val['chip_specification_length'];
            if ($finishedSpecification)
            {
                $finishedSpecification      = str_replace(',', '×', $finishedSpecification);
                $finishedSpecification      .= '厘米';
                $tempArr['finished_specification']   = $finishedSpecification;
            }else{
                //null值处理
                $tempArr['finished_specification']   =  '';
            }


            $orderTypeTitle             = \App\Engine\OrderType::getOneValueById($val['order_type'], 'title');
            $tempArr['order_type_title']     = $orderTypeTitle;

            $orderStatus = $statusColor = '';
            //订单状态调整 zhuyujun 20180623
            if(isset($val['is_deal_price']) && !$val['is_deal_price']){
                //用订单议定价格状态
                $orderStatus=$statusColor='';
                $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$val['id']])->first();
                if($customerOrderPriceObj){
                    $customerOrderPriceStatus = $customerOrderPriceObj->status;
                    $customerOrderPriceStatusArr = config('order.customer_order_price_status_list');

                    //如果是客商，在下单人报价时状态始终不变
                    $userId = Func::getHeaderValueByName('userid',25);
                    $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
                    if($userInfo['company_id'] == 2 && $userInfo['privilege_id'] == 110){
                        if(in_array($customerOrderPriceStatus,[2,3])){
                            $customerOrderPriceStatus = 1;
                        }
                    }

                    if(isset($customerOrderPriceStatusArr[$customerOrderPriceStatus])){
                        $orderStatus = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['txt'];
                        $statusColor    = $customerOrderPriceStatusArr[$customerOrderPriceStatus]['color'];
                    }else{
                        $orderStatus = '';
                        $statusColor    = 'FE7E57';
                    }
                }

            }else{
                if(isset($statusList[$val['status']]))
                {
                    $statusArr      = $statusList[$val['status']];
                    $orderStatus    = $statusArr['txt'];
                    $statusColor    = $statusArr['color'];
                }
            }

            $tempArr['$orderStatus']    = $orderStatus;
            $tempArr['$statusColor']    = $statusColor;
            $productOrderTime                 = date('Y-m-d',$val['created_at']);
            $tempArr['productOrderTime']    = $productOrderTime;
            $tempArr['money']    = 0;
            $tempArr['seller_company_name']    = '';


            $tempArr['order_title'] = \App\Engine\Common::changeSnCode($tempArr['order_title']);

            $result[$valId]         = $tempArr;
        }
        return $result;
    }
    //取一个分组外键对应的所有消息
    public static function getListByForeignKey($whereArr,$userId,$messageId,$limit='',$offset='')
    {
        $where              = ['id'=>$messageId];
        $infoCollection     = self::getInfo($where);
        if(!$infoCollection){
            //兼容删除导致的问题
            $infoCollection = self::withTrashed()->where($where)->first();
        }
        $lists              = $message = [];
        $count              = 0;
        if($infoCollection)
        {
            $message        = $infoCollection->toArray();
            $toUserId       = $message['to_user_id'];
            $foreignType    = $message['foreign_type'];
            $foreignKey     = $message['foreign_key'];
            if($toUserId == $userId )
            {
                $where          = $whereArr;
                $where['to_user_id']    = $userId;
                $where['foreign_type']  = $foreignType;
                $where['foreign_Key']   = $foreignKey;
                $orderby        = ['id','asc'];
                $collection     = self::getList($where,'',$limit,$offset,$orderby);
                $lists          = $collection->toArray();
                $userIdArr      = [];
                foreach($lists as $key=>$val)
                {
                    $userIdArr[]    = $val['form_user_id'];
                }
                $userList           = [];
                if($userIdArr)
                {
                    $where          = ['id'=>['in',$userIdArr]];
                    $userList       = \App\Eloquent\Ygt\User::getList($where)->toArray();
                }
                $lists          = self::changeData($lists,$userList);
                $count          = self::getCount($where);
            }
        }
        $result     = ['list'=>$lists,'count'=>$count];
        return $result;
    }
    //转换消息内容的返回格式
    public static function changeData($data,$userList=[])
    {
        $avatarArr              = $nameArr = [];
        foreach ($userList as $key=>$val)
        {
            $avatarArr[$val['id']]  = $val['avatar'];
            $nameArr[$val['id']]    = $val['truename'];
        }
        $nowTime                = $_SERVER['REQUEST_TIME'];
        $nowYmd                 = date('Y-m-d',$nowTime);
        $todayTime              = strtotime($nowYmd);
        $avatarHttp             = asset('upload/appicon/logo.png');
        $typeList               = self::getTypeList();
        $result                 = [];
        foreach( $data as $key=>$val )
        {
            $arr                = $val;
            unset($arr['content']);

            $fromUserId         = $val['form_user_id'];
            $valType            = $val['type'];
            $valTitle           = $val['title'];
            if(isset($typeList[$valType])){
                $typeArr        = $typeList[$valType];
            }else{
                $typeArr        = $typeList['str'];
            }

            $typeTitle          = $typeArr['title'];
            if(!empty($nameArr))
            {
                if(isset($nameArr[$fromUserId]))
                {
                    if(!empty($val['form_user_name'])){
                        $typeTitle = $val['form_user_name'];
                    }
                    else{
                        $typeTitle  = $nameArr[$fromUserId];
                    }
                }
            }
            $arr['title']      = $typeTitle;

            $buttonTitle        = $typeArr['button_title'];
            $arr['button_title'] = $buttonTitle;

            $typeUrl            = $typeArr['url'];
            if($typeUrl != '')
            {
                $search             = '#type_id#';
                $replace            = $arr['type_id'];
                $typeUrl            = str_replace($search,$replace,$typeUrl);
            }
            $arr['url']            = $typeUrl;

            $contentList            = [];
            $contentTitle           = $typeArr['content_title'];
            $contentTitle['title']  = $valTitle;
            $contentList[]          = $contentTitle;

            $content                = $typeArr['content'];
            $content_arr            = explode( 'rnrn', $val['content'] );
            foreach( $content_arr as $k=>$v )
            {
                $content['title']  = $v;
                $contentList[]      = $content;
            }
            $valTypeStatus          = $val['type_status'];
            $typeStatusList         = $typeArr['type_status'];
            if( isset($typeStatusList[$valTypeStatus]) )
            {
                $typeStatusArr      = $typeStatusList[$valTypeStatus];
                $contentList[]      = $typeStatusArr;
            }
            $arr['content_list']  = $contentList;

            $created_at           = $val['created_at'];
//            $arr['times_ymd']   = date( 'n月d日 H:i', $created_at );
            if($created_at > $todayTime){
                $timesYmd       = date( 'H:i', $created_at );
            }else{
                $timesYmd       = date( 'n月d日', $created_at );
            }
            $arr['times_ymd']   = $timesYmd;
            $iconUrl            = $avatarHttp;
            if(!empty($avatarArr))
            {
                if(isset($avatarArr[$fromUserId]))
                {
                    $avatar          = $avatarArr[$fromUserId];
                    $avatarUrl       = Func::getImgUrlById($avatar);
                    $iconUrl         = $avatarUrl ? $avatarUrl : $iconUrl;
                }
            }
            $arr['icon_url']    = $iconUrl;

            $result[]           = $arr;
        }
        return $result;
    }
    public static function getTypeList(){

        $typeArr                = config('message.type_list');
        $orderArr               = config('message.order_arr');
        $productArr             = config('message.product_arr');
        $orderTitle             = '工单';
        $productTitle           = '仓库';
        $contentTitleDefault    = ['font_color'=>'#333333', 'font_size'=>'16'];
        $content_default        = ['font_color'=>'#888888', 'font_size'=>'13'];
        $defaultArr             = [
            'title'=>'消息', 'content_title'=>$contentTitleDefault,
            'content'=>$content_default, 'button_title'=>'',
            'url'=>'','type_status'=>[]
        ];
        $result                         = [ 'str'=>$defaultArr ];
        foreach( $typeArr as $key=>$val)
        {
            $defaultArr['type_status']  = [];
            $defaultArr['url']          = '';
            if(in_array($key,$orderArr))
            {
                $defaultArr['title']    = $orderTitle;
            }
            if(in_array($key,$productArr))
            {
                $defaultArr['title']    = $productTitle;
            }
            switch ($key)
            {
                case 1:
                    $defaultArr['type_status']  = [
                        1=>['title'=>'待开工','font_color'=>'#FFB401', 'font_size'=>'13'],
                        2=>['title'=>'待领材','font_color'=>'#00AAEE', 'font_size'=>'13'],
                        3=>['title'=>'已开工','font_color'=>'#00AAEE', 'font_size'=>'13'],
                        4=>['title'=>'已完工','font_color'=>'#00AAEE', 'font_size'=>'13'],
                    ];
                    break;
                case 2:
                    $defaultArr['type_status']  = [
                        1=>['title'=>'需接单','font_color'=>'#FFB401', 'font_size'=>'13'],
                        2=>['title'=>'需分配','font_color'=>'#FE7E57', 'font_size'=>'13'],
                        3=>['title'=>'已分配','font_color'=>'#00AAEE', 'font_size'=>'13'],
                    ];
                    break;
                case 3:
                    $defaultArr['type_status']  = [
                        1=>['title'=>'生产中','font_color'=>'#FE7E57', 'font_size'=>'13'],
                        2=>['title'=>'已完工','font_color'=>'#00AAEE', 'font_size'=>'13'],
                    ];
                    break;
                case 11:
                    $url                        = env('APP_URL');
                    $url                        .= '/mobile/order/orderReport?order_report_id=#type_id#';
                    $defaultArr['url']          = $url;
                    break;
                case 15:
                    $defaultArr['type_status']  = [
                        1=>['title'=>'生产中','font_color'=>'#FE7E57', 'font_size'=>'13'],
                        2=>['title'=>'已完工','font_color'=>'#00AAEE', 'font_size'=>'13'],
                    ];
                    break;
                default:
                    /////////
            }
            $result[$key]       = $defaultArr;
        }
        $result[10]['title']    = '采购';
        $result[11]['title']    = '工单报表';
        $result[12]['title']    = '材料领取';
        return $result;
    }
    //改变消息类型的状态
    public static function updateTypeStatus($messageId,$userId,$newTypeStatus)
    {
        $where              = ['to_user_id'=>$userId,'id'=>$messageId];
        $data               = ['type_status'=>$newTypeStatus];
        $result             = self::updateOneData($where,$data);
        return $result;
    }
    //改变消息类型的状态
    public static function updateTypeStatusByTypeId($type,$typeId,$toUserId,$newTypeStatus)
    {
        $where              = [
            'to_user_id'=>$toUserId,'type'=>$type,'type_id'=>$typeId
        ];
        $data               = ['type_status'=>$newTypeStatus];
        $result             = self::updateOneData($where,$data);
        return $result;
    }
    //读取一条消息
    public static function readOne($userId, $messageId)
    {
        $where          = ['to_user_id'=>$userId,'id'=>$messageId];
        $data           = ['is_read'=>1];
        $result         = self::updateOneData( $where, $data );
        return $result;
    }
    //删除一条消息
    public static function deleteOne($userId, $messageId)
    {
        $where              = ['to_user_id'=>$userId,'id'=>$messageId];
        $result             = self::del( $where );
        return $result;
    }
    //删除一条消息
    public static function deleteOneByTypeId($userId, $type, $typeId)
    {
        $where              = [
            'to_user_id'=>$userId,'type'=>$type,'type_id'=>$typeId
        ];
        $result             = self::del( $where );
        return $result;
    }
}